package com.siteseat.crudeq.kernel.scheduler;

import java.util.concurrent.ConcurrentHashMap;

import com.siteseat.common.foundation.PropertyHelper;
import com.siteseat.common.foundation.ScheduledActor;
import com.siteseat.crudeq.kernel.impl.PersistedChunkManager;

/**
 * 
 */
public abstract class StoreScheduler extends ScheduledActor {

  private ConcurrentHashMap<Integer, PersistedChunkManager> managers 
    = new ConcurrentHashMap<Integer, PersistedChunkManager>();

  /**
   * Gets the manager
   * 
   * @return the manager
   */
  public ConcurrentHashMap<Integer, PersistedChunkManager> getManagers() {
    return managers;
  }

  public void addManager( PersistedChunkManager mgr ) {
    getManagers().put( mgr.getQueueId(), mgr );
  }

  public void removeManager( Integer qid ) {
    getManagers().remove( qid );
  }

  /**
   * Sets the manager
   * 
   * @param pools
   *          the manager to set
   */
  public void setManagers( ConcurrentHashMap<Integer, PersistedChunkManager> managers ) {
    this.managers = managers;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  protected void doInit() throws Exception {
    super.doInit();

    PropertyHelper.ensureInitialized( log, getManagers(), "managers" );

    startScheduler();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  protected void onScheduled() throws InterruptedException {
    for( PersistedChunkManager p: getManagers().values() ) {
      try {
        doScheduledJob( p );
      } catch( Exception e ) {
        log.error( "Error during executing scheduled job on pool <" + p.getProfile(), e );
      }
    }
  }

  /**
   * @param p
   * @throws Exception
   */
  protected abstract void doScheduledJob( PersistedChunkManager p ) throws Exception;

}
